package com.wf.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.wf.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalDateTime;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if(principal instanceof SysUser)
        {
            SysUser sysUser = (SysUser) principal;
            this.strictInsertFill(metaObject, "createUser", String.class, sysUser.getUserId());
        }
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "isDeleted", Integer.class, 0);

    }

    @Override
    public void updateFill(MetaObject metaObject) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication instanceof SysUser)
        {
            SysUser sysUser = (SysUser) authentication.getPrincipal();
            this.strictInsertFill(metaObject, "updateUser", String.class, sysUser.getUserId());
        }
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}